﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Windows.Forms;
using System.Text.RegularExpressions;
using System.Collections;

namespace NutWinFrm
{
    public partial class FileWorker : Form
    {
        /// <summary>
        /// 保存处理后的文件
        /// </summary>
        string dir_merge = @"\merge";
        /// <summary>
        /// 保存重复名字的文件
        /// </summary>
        String dir_more = @"\more";
        /// <summary>
        /// 存放不符合规则的文件
        /// </summary>
        string dir_default = @"\others";

        /// <summary>
        /// 运行日志
        /// </summary>
        String log_file = @"\trace.log";

        String log_file_more = @"\trace_more.log";
        String log_file_right = @"\trace_right.log";
        /// <summary>
        /// 生成视频剪切的文件地址
        /// </summary>
        String video_cut_xml = @"\1.xml";
        /// <summary>
        /// 默认对照名称
        /// </summary>
        string default_key = "default";

        /// <summary>
        /// 保存运行的名称对照
        /// </summary>
        Hashtable fileNameMap = new Hashtable();

        public delegate void DoFile(String fileName);
        // BatchName batchName = new FileWorker.g
        public DoFile moveAndRename;
        public DoFile onlyRename;
        public DoFile makeVideoCut;

        public FileWorker()
        {
            InitializeComponent();

            moveAndRename = new DoFile(moveAndRenameImp);
            makeVideoCut = new DoFile(makeVideoCutImp);
            onlyRename = new DoFile(onlyRenameImp);

        }

        public void init()
        {
            dir_merge = @"\merge";
            dir_more = @"\more";
            dir_default = @"\others";

            log_file = @"\trace.log";

            log_file_more = @"\trace_more.log";
            log_file_right = @"\trace_right.log";

            video_cut_xml = @"\1.xml";

        }

        private void button_run_Click(object sender, EventArgs e)
        {
            init();
            if (!Directory.Exists(folderBrowserDialog_src.SelectedPath)
                || String.IsNullOrEmpty(folderBrowserDialog_src.SelectedPath))
            {
                MessageBox.Show("源目录不存在存在");
                return;
            }


            if (!Directory.Exists(folderBrowserDialog_output.SelectedPath)
                 || String.IsNullOrEmpty(folderBrowserDialog_output.SelectedPath))
            {
                MessageBox.Show("输出目录不存在");
                return;
            }

            log_file = folderBrowserDialog_output.SelectedPath + log_file;
            log_file_more = folderBrowserDialog_output.SelectedPath + log_file_more;
            log_file_right = folderBrowserDialog_output.SelectedPath + log_file_right;
            try
            {

                File.Delete(log_file);
                File.Delete(log_file_more);
                File.Delete(log_file_right);
            }
            catch (Exception e1)
            {
                Console.WriteLine("发生例外" + e1.Message);

            }


            dir_merge = folderBrowserDialog_output.SelectedPath + dir_merge;

            dir_more = folderBrowserDialog_output.SelectedPath + dir_more;

            dir_default = folderBrowserDialog_output.SelectedPath + dir_default;
            if (!Directory.Exists(dir_merge))
            {
                Directory.CreateDirectory(dir_merge);
            }
            if (!Directory.Exists(dir_more))
            {
                Directory.CreateDirectory(dir_more);
            }
            if (!Directory.Exists(dir_default))
            {
                Directory.CreateDirectory(dir_default);
            }
            doDir(folderBrowserDialog_src.SelectedPath, moveAndRename);
            foreach (DictionaryEntry entry in fileNameMap)
            {


                ArrayList _list = fileNameMap[entry.Key.ToString()] as ArrayList;

                foreach (String v in _list)
                {
                    if (entry.Key.ToString().Equals(default_key))
                    {
                        trace_file_right(entry.Key.ToString() + "," + v);

                    }

                    else if (_list.Count > 1)
                    {
                        trace_file_more(entry.Key.ToString() + "," + v);
                    }
                    else
                    {
                        trace_file_right(entry.Key.ToString() + "," + v);
                    }
                }

            }


        }
        /// <summary>
        /// 按目录进行移动处理
        /// </summary>
        /// <param name="path"></param>
        public void doDir(String path, DoFile worker)
        {
            try
            {
                String[] fs = Directory.GetFiles(path);
                foreach (string name in fs)
                {
                    FileInfo fi = new FileInfo(name);
                    if (fi.Length > 1048576)
                    {
                        worker(name);
                    }
                }

                String[] dirs = Directory.GetDirectories(path);
                foreach (string name in dirs)
                {
                    doDir(name, worker);
                }
            }
            catch (Exception e)
            {

                Console.WriteLine("目录" + path + "发生例外" + e.Message);
                Console.WriteLine(e.StackTrace);
            }

        }
        /// <summary>
        /// 移动时，对文件的处理
        /// </summary>
        /// <param name="name"></param>
        public void moveAndRenameImp(String name)
        {
            try
            {
                FileInfo fs = new FileInfo(name);
                String newName = getName(fs.Name);

                String fullName = "";

                if (!String.IsNullOrEmpty(newName))
                {
                    String _t = fs.Name.Replace(newName, "");
                    if (_t.StartsWith("_"))
                    {
                        fullName = newName + _t;
                    }
                    else
                    {
                        fullName = newName + "_" + _t;
                    }

                    fullName = fullName.Replace("_.", ".");
                    fullName = fullName.Replace("__", "_");
                }
                else
                {
                    fullName = fs.Name;
                }
                fullName = fullName.ToUpper();




                String des = dir_merge + "\\" + fullName;
                string des_rs = getSaveAutoName(des);
                if (String.IsNullOrWhiteSpace(newName))
                {

                    ///不规则文件名
                    /// 
                    newName = default_key;
                    des_rs = getSaveAutoName(dir_default + "\\" + fullName);

                }
                else if (!des.Equals(des_rs))
                {
                    //no exist file

                    des_rs = getSaveAutoName(dir_more + "\\" + fullName);
                }

                ///move file
                fs.MoveTo(des_rs);

                ///记录对照关系
                if (fileNameMap.Contains(newName))
                {
                    ArrayList _list = (ArrayList)fileNameMap[newName];
                    _list.Add(des_rs);

                }
                else
                {
                    ArrayList _list = new ArrayList();
                    _list.Add(des_rs);
                    fileNameMap.Add(newName, _list);

                }
                trace("文件" + name + "结束");
            }
            catch (Exception e)
            {
                trace("文件" + name + "发生例外" + e.Message);
                Console.WriteLine("文件" + name + "发生例外" + e.Message);
                Console.WriteLine(e.StackTrace);
            }

        }

        /// <summary>
        /// 移动时，对文件的处理
        /// </summary>
        /// <param name="name"></param>
        public void onlyRenameImp(String name)
        {
            try
            {
                FileInfo fs = new FileInfo(name);


                String fullName = fs.Name;

                fullName = fullName.Replace("_.", ".");
                fullName = fullName.Replace("__", "_");



                fullName = fullName.ToUpper();
                String des = fs.DirectoryName + "\\" + fullName;
                string des_rs = getSaveAutoName(des);
                ///move file
                fs.MoveTo(des_rs);


                trace("文件" + name + "结束");
            }
            catch (Exception e)
            {
                trace("文件" + name + "发生例外" + e.Message);
                Console.WriteLine("文件" + name + "发生例外" + e.Message);
                Console.WriteLine(e.StackTrace);
            }

        }
        /// <summary>
        /// 生成视频剪切配置
        /// </summary>
        /// <param name="name"></param>
        public void makeVideoCutImp(String name)
        {
            try
            {
                FileInfo fs = new FileInfo(name);
                String shortName = fs.Name.Replace(fs.Extension, "");
                shortName = shortName + "_01"+fs.Extension;
                shortName = folderBrowserDialog_output.SelectedPath + "\\" + shortName;
                File.AppendAllText(video_cut_xml, "	<timeline>\r\n");
   File.AppendAllText(video_cut_xml, "		<group output=\""+shortName+"\" >\r\n");
                File.AppendAllText(video_cut_xml, "			<track video=\"1\" audio=\"1\" text=\"0\" accuracy=\"frame\" >\r\n");
                File.AppendAllText(video_cut_xml, "				 <clip src=\""+fs.FullName+"\"  start=\"00:01:00.00\"  stop=\"10:07:00.00\"  />\r\n");
                File.AppendAllText(video_cut_xml, "			</track>\r\n");
                File.AppendAllText(video_cut_xml, "		</group>\r\n");
                File.AppendAllText(video_cut_xml, "	</timeline>\r\n");




                trace("文件" + name + "结束");
            }
            catch (Exception e)
            {
                trace("文件" + name + "发生例外" + e.Message);
                Console.WriteLine("文件" + name + "发生例外" + e.Message);
                Console.WriteLine(e.StackTrace);
            }

        }



        public void trace(String value)
        {
            File.AppendAllText(log_file, value + "\n");
            richTextBox_log.AppendText(value + "\n");

        }

        public void trace_file_more(String value)
        {
            File.AppendAllText(log_file_more, value + "\n");
            richTextBox_wrong.AppendText(value + "\n");

        }

        public void trace_file_right(String value) 
        {
            File.AppendAllText(log_file_right, value + "\n");
            richTextBox_short.AppendText(value + "\n");

        }

        public String getName(String filename)
        {

            //[a-zA-z]{2,4}-\d{2,4}  aaa-bbb

            String name = "";
            Regex patten = new Regex(@"[a-zA-Z]{2,6}-\d{2,8}");
            MatchCollection mc = patten.Matches(filename);

            foreach (Match item in mc)
            {
                if (String.IsNullOrEmpty(name))
                    name = item.Value;
                else
                {
                    name += "_" + item.Value;
                }
            }

            return name;


        }

        public String getSaveAutoName(String fileName)
        {
            String oldName = fileName;

            for (int i = 0; File.Exists(oldName); i++)
            {
                oldName = fileName + "." + i;
            }
            return oldName;
        }

        private void button_select_dir_Click(object sender, EventArgs e)
        {
            folderBrowserDialog_src.ShowDialog();
            textBox1.Text = folderBrowserDialog_src.SelectedPath;
        }

        private void button_output_dir_Click(object sender, EventArgs e)
        {
            folderBrowserDialog_output.ShowDialog();
            textBox2.Text = folderBrowserDialog_output.SelectedPath;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            init();
            if (!Directory.Exists(folderBrowserDialog_src.SelectedPath)
               || String.IsNullOrEmpty(folderBrowserDialog_src.SelectedPath))
            {
                MessageBox.Show("源目录不存在存在");
                return;
            }
            if (!Directory.Exists(folderBrowserDialog_output.SelectedPath)
              || String.IsNullOrEmpty(folderBrowserDialog_output.SelectedPath))
            {
                MessageBox.Show("输出目录不存在存在");
                return;
            }

            String[] fs = Directory.GetFileSystemEntries(folderBrowserDialog_src.SelectedPath);
            foreach (String str in fs)
            {
                FileInfo file = new FileInfo(str);
                String name = file.Name;
                if (name.StartsWith("_"))
                {
                    name = name.Substring(1);
                }

                int index = name.IndexOf("_");
                String name2 = name.Substring(index + 1);

                file.MoveTo(folderBrowserDialog_output.SelectedPath + "\\" + name2);



                richTextBox_log.AppendText("\n" + name2 + "," + name);
                richTextBox_log.AppendText("\n" + folderBrowserDialog_output.SelectedPath + "\\" + name2);
            }
        }
        /// <summary>
        /// 生成可以剪切的信息
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button3_Click(object sender, EventArgs e)
        {
            init();
            if (!Directory.Exists(folderBrowserDialog_src.SelectedPath)
                || String.IsNullOrEmpty(folderBrowserDialog_src.SelectedPath))
            {
                MessageBox.Show("源目录不存在存在");
                return;
            }


            if (!Directory.Exists(folderBrowserDialog_output.SelectedPath)
                 || String.IsNullOrEmpty(folderBrowserDialog_output.SelectedPath))
            {
                MessageBox.Show("输出目录不存在");
                return;
            }

            log_file = folderBrowserDialog_output.SelectedPath + log_file;
            log_file_more = folderBrowserDialog_output.SelectedPath + log_file_more;
            log_file_right = folderBrowserDialog_output.SelectedPath + log_file_right;
            try
            {

                File.Delete(log_file);
                File.Delete(log_file_more);
                File.Delete(log_file_right);
            }
            catch (Exception e1)
            {
                Console.WriteLine("发生例外" + e1.Message);

            }

            video_cut_xml = folderBrowserDialog_output.SelectedPath + "\\" + video_cut_xml;

            File.AppendAllText(video_cut_xml, "<timelines version=\"2\" >");


            doDir(folderBrowserDialog_src.SelectedPath, makeVideoCut);
            File.AppendAllText(video_cut_xml, "</timelines>");
            MessageBox.Show("end ");
            
        }
    }
}
